package com.bootcamp.servlet.defaultservlet;

/**
 * @program: wrok-1101
 * @description: ${description}
 * @author: Keyu Li
 * @create: 2021-11-02 14:34
 **/

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

@WebServlet(name = "MyDefaultServlet", value = "/")
public class MyDefaultServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String fileName = request.getServletPath();
        String filePath = request.getServletContext().getRealPath(fileName);
        File file = new File(filePath);
        if (!file.exists()||!file.isFile()) {
            // 如果文件不存咋，返回404
            respond404(response);
            return;
        }
        // 文件存在，则返回该文件
        //System.out.println("find file! "+filePath);
        respond200File(file, response);
    }

    private void respond200File(File file, HttpServletResponse response) {
        FileInputStream fileInputStream = null;
        ServletOutputStream outputStream = null;
        try {
            fileInputStream = new FileInputStream(file);
            outputStream = response.getOutputStream();

            // 一读一写
            byte[] bytes = new byte[1024];
            int length;
            while ((length = fileInputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, length);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fileInputStream.close();
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void respond404(HttpServletResponse response) {
        response.setStatus(404);
        try {
            response.getWriter().println("File Not found!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
